package com.liurong.netty.v2.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ChatClientHandler extends SimpleChannelInboundHandler<String> {

	private ChatClient chatClient;

	public ChatClientHandler() {
		super();
	}

	public ChatClientHandler(ChatClient chatClient) {
		this.chatClient = chatClient;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.out.println(msg);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			String type = "";
			if (event.state() == IdleState.READER_IDLE) {
				type = "read idle";
			} else if (event.state() == IdleState.WRITER_IDLE) {
				type = "write idle";
			} else {
				type = "all idle";
			}
			ctx.writeAndFlush("heartbeat");
			System.out.println(ctx.channel().remoteAddress() + "超时类型：" + type);
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("异常原因:" + cause);
		// 在这里可以做成等待服务端起来再重新连接
		// 模拟重连
		System.out.println("服务端连接异常，客户端发起重连！" + ctx.channel().remoteAddress());
		// 先关闭之前的连接
		ctx.close();

		chatClient.connect();
	}
}
